package show.me.the.money.resource;

import java.io.IOException;
import java.util.HashMap;


public class ResourceFileController {
	private String sBasePath = "";
	private static HashMap<String,ResourceFile> oCacheFiles = new HashMap<String,ResourceFile>();
	
	public ResourceFileController(String sBasePath){
		this.sBasePath = sBasePath;
	}

	@SuppressWarnings("unchecked")
	public ResourceFile getResourceFile(String sClsName,Class oCls) throws InstantiationException, IllegalAccessException, IOException{
		ResourceFile oResFile = findInCache(sClsName);
		if(oResFile == null){
			int p = sClsName.lastIndexOf(".");
			String sPrefix = sClsName.substring(0,p);
			String sPostfix = sClsName.substring(p + 1);
			String sFileName = sBasePath + "/" + 
			                   sPrefix.replaceAll("\\.","/") + 
			                   "." + sPostfix;
			oResFile = 	(ResourceFile)oCls.newInstance();
			oResFile.setFileName(sFileName);
			oResFile.setPostfix(sPostfix);
			if(oResFile.exists()){
				putIntoCache(sClsName,oResFile);
			}
		}
		oResFile.load();
		return oResFile;
		
	}

	private ResourceFile findInCache(String sClsName){
		if(oCacheFiles.containsKey(sClsName)){
			return oCacheFiles.get(sClsName);
		}
		return null;
		
	}
	
	private void putIntoCache(String sClsName,ResourceFile oResFile){
		oCacheFiles.put(sClsName,oResFile);
	}
}
